package com.yenlien.traceyun.business.service;

import com.yenlien.traceyun.business.dao.StorageManageDetailedDao;
import com.yenlien.traceyun.business.entity.StorageManageDetailed;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class StorageManageDetailedService {
    @Autowired
    private StorageManageDetailedDao storageManageDetailedDao;

    public Page<StorageManageDetailed> findByList(final StorageManageDetailed storageManageDetailed) {
        Pageable pageable = PageRequest.of(storageManageDetailed.getPage(), storageManageDetailed.getPageSize(), Sort.Direction.DESC, ("createtime"));
        return storageManageDetailedDao.findAll(new Specification<StorageManageDetailed>() {
            private static final long serialVersionUID = -1396496630802017658L;

            @Override
            public Predicate toPredicate(Root<StorageManageDetailed> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> productName = root.get("productName");
                Path<String> processBatch = root.get("processBatch");
                Path<String> type = root.get("type");
                //构造查询条件
                List<Predicate> list = new ArrayList<Predicate>();
                list.add(cb.equal(type, storageManageDetailed.getType()));
                Predicate[] predicateA = new Predicate[list.size()];
                Predicate predicateAnd = cb.and(list.toArray(predicateA));
                if (StringUtils.isNotEmpty(storageManageDetailed.getProductName())) {
                    List<Predicate> list2 = new ArrayList<>();
                    list2.add(cb.like(productName, "%" + storageManageDetailed.getProductName() + "%"));
//                    list2.add(cb.like(processBatch, "%" + storageManageDetailed.getProcessBatch() + "%"));
                    Predicate[] predicateO = new Predicate[list2.size()];
                    Predicate predicateOr = cb.or(list2.toArray(predicateO));
                    return query.where(predicateAnd, predicateOr).getRestriction();
                } else {
                    return predicateAnd;
                }
            }
        }, pageable);
    }
}
